package com.kotiln.lgc.sunnyweather.logic.dao

import android.util.Log
import androidx.lifecycle.liveData
import com.kotiln.lgc.sunnyweather.logic.model.Place
import com.kotiln.lgc.sunnyweather.logic.model.Weather
import com.kotiln.lgc.sunnyweather.logic.network.SunnyWeatherNetwork
import com.kotiln.lgc.sunnyweather.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlin.coroutines.CoroutineContext

/**
 *@fileName Repository
 *@date2020/11/27  13:43
 *@author Repository$
 *@describe TODO
 *@desc 仓库层
 */
object Repository {

    fun savePlace(place: Place)=PlaceDao.savePlace(place)
    fun getSavedPlace()=PlaceDao.getSavePlace()
    fun isPlaceSaved()=PlaceDao.isPlaceSaved()


    fun searchPlaces(query: String) = fire(Dispatchers.IO) {
        val placeResponse = SunnyWeatherNetwork.searchPlaces(query)
        Log.i("placeResPonse", placeResponse.toString())
        // PlaceResponse(status=ok, places=[Place(name=中国 北京市 北京, location=Location(lng=116.405285, lat=39.904989), address=中国 北京市 北京), Place(name=中国 北京市 延庆, location=Location(lng=115.985006, lat=40.465325), address=中国 北京市 延庆)])
        if (placeResponse.status == "ok") {
            val places = placeResponse.places

            Log.i("places",places.toString())
            //[Place(name=中国 北京市 北京, location=Location(lng=116.405285, lat=39.904989), address=中国 北京市 北京), Place(name=巴哈马 北伊柳塞拉, location=Location(lng=-76.5368, lat=25.3903), address=巴哈马 北伊柳塞拉), Place(name=特克斯和凯科斯群岛 北凯科斯岛, location=Location(lng=-71.9557, lat=21.8765), address=特克斯和凯科斯群岛 北凯科斯岛), Place(name=斯里兰卡 拜蒂克洛区 北曼姆奈, location=Location(lng=81.7157, lat=7.7159), address=斯里兰卡 拜蒂克洛区 北曼姆奈), Place(name=越南 谅山省 北山县, location=Location(lng=106.2552, lat=21.8155), address=越南 谅山省 北山县)]
            Result.success(places)
        } else {
            Result.failure(RuntimeException("response status is ${placeResponse.status}"))
        }
    }


    fun refreshWeather(lng: String, lat: String) = fire(Dispatchers.IO) {

        coroutineScope {
            val deferredDaily = async {
                SunnyWeatherNetwork.getDailyWeather(lng, lat)
            }
            val deferredRealtime = async {
                SunnyWeatherNetwork.getRealtimeWeather(lng, lat)
            }
            val realtimeResponse = deferredRealtime.await()
            val dailyResponse = deferredDaily.await()
            LogUtil.i("realtimeResponse:", realtimeResponse.status)
            LogUtil.i("dailyResponse", dailyResponse.status)
            if (realtimeResponse.status == "ok" && dailyResponse.status == "ok") {
                val weather = Weather(realtimeResponse.result.realtime, dailyResponse.result.daily)
                Result.success(weather)
            } else {
                Result.failure(RuntimeException("realtime response status is ${realtimeResponse.status}" + "daily response status is ${dailyResponse.status}"))
            }
        }
    }

    private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
        liveData<Result<T>>(context) {
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure<T>(e)
            }
            emit(result)
        }
}